package com.wmcsk.dl.dl.internal;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import java.lang.reflect.Constructor;

import com.wmcsk.dl.dl.DLBroadcastPlugin;
import com.wmcsk.dl.dl.utils.DL;
import com.wmcsk.dl.dl.utils.DLConfigs;
import com.wmcsk.dl.dl.utils.DLConstants;


/**
 * Created by wm on 2016/11/29.
 */

public class DLBroadcastProxyImpl {
    private static final String TAG = DLServiceProxyImpl.class.getName();
    private BroadcastReceiver mProxyBroadcastReceiver;
    private DLBroadcastPlugin mRemoteBroadcastReceiver;
    public DLBroadcastProxyImpl(BroadcastReceiver broadcastReceiver) {
        mProxyBroadcastReceiver = broadcastReceiver;
    }
    public void onReceive(Context context, Intent intent){
        intent.setExtrasClassLoader(DLConfigs.sPluginClassloader);
        String packageName = intent.getStringExtra(DLConstants.EXTRA_PACKAGE);
        String clazz = intent.getStringExtra(DLConstants.EXTRA_CLASS);
        DL.d(TAG, "clazz=" + clazz + " packageName=" + packageName);
        DLPluginManager pluginManager = DLPluginManager
                .getInstance(context);
        DLPluginPackage pluginPackage = pluginManager.getPackage(packageName);
        try{
            Class<?> localClass = pluginPackage.classLoader.loadClass(clazz);
            Constructor<?> localConstructor = localClass
                    .getConstructor(new Class[] {});
            Object instance = localConstructor.newInstance(new Object[] {});
            mRemoteBroadcastReceiver = (DLBroadcastPlugin) instance;
            ((DLBroadcastReciverAttachable) mProxyBroadcastReceiver).attach(mRemoteBroadcastReceiver,
                    pluginManager);
            DL.d(TAG, "instance = " + instance);
            // attach the proxy activity and plugin package to the
            // mPluginActivity
            mRemoteBroadcastReceiver.attach(mProxyBroadcastReceiver, pluginPackage);

            Bundle bundle = new Bundle();
            bundle.putInt(DLConstants.FROM, DLConstants.FROM_EXTERNAL);
            //mRemoteBroadcastReceiver.onReceive(context,intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
